<?php
// 测试改进后的食材匹配逻辑

// 数据库配置
$host = '127.0.0.1';
$dbname = 'yingyang';
$username = 'root';
$password = 'root';
$charset = 'utf8mb4';

try {
    $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 测试改进后的食材匹配逻辑 ===\n\n";
    
    // 测试一些常见的食材名称
    $testIngredients = [
        '木耳',
        '大蒜',
        '盐',
        '西兰花',
        '姜片',
        '料酒',
        '白菜',
        '醋'
    ];
    
    foreach ($testIngredients as $ingredientName) {
        echo "测试食材: $ingredientName\n";
        
        // 精确匹配
        $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name = ?');
        $stmt->execute([$ingredientName]);
        $exactMatch = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($exactMatch) {
            echo "  ✓ 精确匹配: ID={$exactMatch['id']}, 名称={$exactMatch['name']}\n";
            continue;
        } else {
            echo "  ✗ 无精确匹配\n";
        }
        
        // 方式1: 名称包含食材名
        $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name LIKE ? ORDER BY id LIMIT 1');
        $stmt->execute(["%$ingredientName%"]);
        $match1 = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($match1) {
            echo "  ~ 方式1匹配: ID={$match1['id']}, 名称={$match1['name']}\n";
            continue;
        }
        
        // 方式2: 食材名包含名称中的关键词
        $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name LIKE ? ORDER BY id LIMIT 1');
        $stmt->execute([$ingredientName . '%']);
        $match2 = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($match2) {
            echo "  ~ 方式2匹配: ID={$match2['id']}, 名称={$match2['name']}\n";
            continue;
        }
        
        echo "  ✗ 无任何匹配\n";
        echo "\n";
    }
    
    echo "=== 测试特定案例 ===\n\n";
    
    // 测试西兰花案例
    echo "测试西兰花:\n";
    $stmt = $pdo->prepare('SELECT id, name, parent_id, categories_id FROM fa_food_ingredient WHERE name LIKE ? OR name LIKE ? ORDER BY id');
    $stmt->execute(['%西兰花%', '西兰花%']);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($results as $result) {
        echo "  ID={$result['id']}, 名称={$result['name']}\n";
    }
    
} catch (Exception $e) {
    echo "执行失败: " . $e->getMessage() . "\n";
}
?>